function hfile = root_Document(hfile, dspec)
% ROOT::Document  - get one "Document" (VB-Style interface)
%
% FORMAT:       object = BVQXfile.Document(dspec);
%
% Input fields:
%
%       dspec       either numbered object or (partial) filename
%
% Output fields:
%
%       object      found object (otherwise: error)

% Version:  v0.7g
% Build:    9100621
% Date:     Oct-06 2009, 9:27 PM CEST
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin ~= 2 || ...
    numel(hfile) ~= 1 || ...
   ~isBVQXfile(hfile, 'root') || ...
    hfile.L ~= 1 || ...
   (~isa(dspec, 'double') && ...
    ~ischar(dspec)) || ...
    isempty(dspec)
    error( ...
        'BVQXfile:BadArgument', ...
        'Invalid call to ''%s''.', ...
        mfilename ...
    );
end

% get available objects (without ROOT!)
o = BVQXfile(0, 'objects');
o(1) = [];

% for strings, look for filename match
if ischar(dspec)
    dspec = dspec(:)';
    ons = {o(:).F};
    fm = findfirst(strcmpi(dspec, ons));
    if isempty(fm)
        for c = 1:numel(ons)
            [p, f, e] = fileparts(ons{c});
            ons{c} = [f, e];
        end
        [p, f, e] = fileparts(dspec);
        f = [f, e];
        fm = findfirst(strcmpi(f, ons));
    end
    if ~isempty(fm)
        hfile = BVQXfile(0, 'makeobject', struct('L', o(fm).L));
    else
        error( ...
            'BVQXfile:LookupError', ...
            'Error finding file %s in object list.', ...
            dspec ...
        );
    end
    
% invalid double index lookup
elseif numel(dspec) ~= 1 || ...
    isinf(dspec) || ...
    isnan(dspec) || ...
    dspec < 1 || ...
    dspec > numel(o)
    error( ...
        'BVQXfile:LookupError', ...
        'Invalid Document index given.' ...
    );

% valid index
else
    
    % make object
    hfile = BVQXfile(0, 'makeobject', struct('L', o(round(dspec)).L));
end
